#include<math.h>
#include<pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>

#include "Beacon.h"
#include "Constant.h"
#include "ManageRoute.h"

void beacon_init(){
	printf("beacon_init\n");
}

void beacon(){
	sleep(2);
	//char tmp[200];
    char packet[MAX_PACKET_LEN];
    int len;
    int sockfd;

    if( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ){
        perror("D_broadcast---socket.");
        printf("errno:%d\n",errno);
        exit(1);
    }

    int so_broadcast =1;
    setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &so_broadcast, sizeof(so_broadcast));

    struct sockaddr_in broadcast_addr;
    bzero(&broadcast_addr, sizeof(broadcast_addr));
    broadcast_addr.sin_family=AF_INET;
    broadcast_addr.sin_port = htons( BROADCASTPORT );
    if( inet_aton(BROADCASTIP,&broadcast_addr.sin_addr)<0 ){
        perror("beacon---inet_aton.");
        printf("errno:%d\n",errno);
        //beep(2000,2000);
        exit(1);
    }

    //int i=0;
    packet[0]=0x01;
    while(1){
		len = getRouterInfo(packet+1);
		len=len+1;
		if( sendto(sockfd, packet, len, 0, (struct sockaddr *)&broadcast_addr, sizeof(broadcast_addr))<0 ){
			perror("beacon--sendto.");
			printf("errno:%d\n",errno);
		}
		usleep( 1.9*1000000+rand()%200000);//average 2.0s
		//usleep( (BEACON_TIME-10)*1000000+rand()%1000000);
	}
}
